<?php

class CoreModel extends IzwebzCore {

	function __construct()
	{
		parent::__construct();
	}

	public function getTable(){
		$thisTable = get_class($this);
		return $thisTable::returnTable();
	}
	
	public function exist($id)
	{
		$result =  $this->wpdb->get_var("SELECT id FROM {$this->getTable()} WHERE id = {$id}",ARRAY_A);
		if(empty($result->id))
			return false;
		else
			return true;
	}

	public function findById($id,$arrayType = false)
	{
		$outType = $arrayType === true ? 'ARRAY_A' : 'OBJECT';
		return $this->wpdb->get_row("SELECT * FROM {$this->getTable()} WHERE id = {$id}",$outType);
	}

	public function find($conditions = array(), $limit = 10, $order = "id DESC")
	{
		$txtConditions = true;
		if(!empty($conditions)){
			$txtConditions = "";
			$i=1;
			foreach ($conditions as $key => $value) {
				if($i==count($conditions)){
					$txtConditions .= "{$key} = {$value} ";
				}else{
					$txtConditions .= "{$key} = {$value} AND ";
				}
				$i++;
			}

		}

		$sql = "SELECT * FROM {$this->getTable()} WHERE ";
		$sql .="{$txtConditions} ORDER BY {$order} LIMIT {$limit}";

		return $result = $this->wpdb->get_results($sql);
	}

	public function update($arrAttributes = array(),$conditions = array(), $data_format = null, $where_format = null)
	{
		return $this->wpdb->update($this->getTable(), $arrAttributes, $conditions,$data_format,$where_format);
	}

	public function insert($data = array(),$data_format = null)
	{
		$insert = $this->wpdb->insert( $this->getTable(), $data, $data_format);
		if($insert)
			return $this->wpdb->insert_id;
		else
			return fasle;
	}

	public function delete($conditions = array(),$where_format = null)
	{
		return $this->wpdb->delete($this->getTable(),$conditions,$where_format);
	}

}